import {login, logout, getInfo} from '@/api/login'
import {getToken, setToken, removeToken} from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'

// 使用 import.meta.glob 动态导入所有头像
const avatars = import.meta.glob('@/assets/images/avatar/*.png');

const useUserStore = defineStore(
    'user',
    {
        state: () => ({
            token: getToken(),
            id: '',
            name: '',
            avatar: '',
            roles: [],
            permissions: []
        }),
        actions: {
            // 登录
            login(userInfo) {
                const username = userInfo.username.trim()
                const password = userInfo.password
                const code = userInfo.code
                const uuid = userInfo.uuid
                const captchaEnabled = userInfo.captchaEnabled
                return new Promise((resolve, reject) => {
                    login(username, password, code, uuid, captchaEnabled).then(res => {
                        setToken(res.token)
                        this.token = res.token
                        resolve()
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            // 获取用户信息
            async getInfo() {
                try {
                    const res = await getInfo()
                    const user = res.user

                    // 随机选择头像
                    let avatar;
                    if (user.avatar == "" || user.avatar == null) {
                        // 随机选择一个头像
                        avatar = await this.getRandomAvatar();
                    } else {
                        avatar = import.meta.env.VITE_APP_BASE_API + user.avatar;
                    }

                    if (res.roles && res.roles.length > 0) {
                        this.roles = res.roles
                        this.permissions = res.permissions
                    } else {
                        this.roles = ['ROLE_DEFAULT']
                    }
                    this.id = user.userId
                    this.name = user.userName
                    this.avatar = avatar

                    return res
                } catch (error) {
                    throw error
                }
            },
            // 退出系统
            logOut() {
                return new Promise((resolve, reject) => {
                    logout(this.token).then(() => {
                        this.token = ''
                        this.roles = []
                        this.permissions = []
                        removeToken()
                        resolve()
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            // 获取随机头像
            async getRandomAvatar() {
                const avatarPaths = Object.keys(avatars);
                const randomPath = avatarPaths[Math.floor(Math.random() * avatarPaths.length)];
                try {
                    const module = await avatars[randomPath]();
                    return module.default;
                } catch (error) {
                    console.error('Failed to load avatar:', error);
                    return defAva; // 使用默认头像
                }
            },
            // 手动切换头像
            async switchAvatar() {
                try {
                    const newAvatar = await this.getRandomAvatar();
                    this.avatar = newAvatar;
                    // 这里可以添加逻辑来将新头像保存到后端
                    // 例如：await updateUserAvatar(this.id, newAvatar);
                    return newAvatar;
                } catch (error) {
                    console.error('Failed to switch avatar:', error);
                    throw error;
                }
            }
        }
    })

export default useUserStore
